package com.viewpagertext.fragments;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;

import android.annotation.SuppressLint;

import static com.viewpagertext.service.MusicService.mediaPlayer;

import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.PlaybackModeDao;
import com.viewpagertext.DBHelper.Dao.StarredSongDao;
import com.viewpagertext.Lrc.DefaultLrcBuilder;
import com.viewpagertext.Lrc.ILrcBuilder;
import com.viewpagertext.Lrc.ILrcViewListener;
import com.viewpagertext.Lrc.LrcRow;
import com.viewpagertext.R;
import com.viewpagertext.activitys.PlayActivity;
import com.viewpagertext.constructor.ListToPlayEvent;
import com.viewpagertext.constructor.MessageEvent;
import com.viewpagertext.databinding.FragmentSongBinding;
import com.viewpagertext.json.PlaybackMode;
import com.viewpagertext.json.StarredSong;
import com.viewpagertext.utils.HttpUtil;
import com.viewpagertext.utils.TimeUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.media.MediaPlayer.OnPreparedListener;
import android.widget.SeekBar;
import android.widget.Toast;

import jp.wasabeef.glide.transformations.BlurTransformation;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.viewpagertext.activitys.MainActivity.mList;
import static com.viewpagertext.activitys.MainActivity.nowMode;
import static com.viewpagertext.activitys.MainActivity.musicService;
import static com.viewpagertext.activitys.MainActivity.playPosition;
import static com.viewpagertext.adapters.MusicGridAdapter.FindImgUrlPath;
import static com.viewpagertext.adapters.MusicGridAdapter.MyStarredSong;
import static com.viewpagertext.service.MusicService.mediaPlayer;
import static com.viewpagertext.service.MusicService.media_falg;




public class SongFragment extends Fragment {

    StarredSongDao starredSongHelper = AppDatabase.getInstance().starredSongDao();
    PlaybackModeDao playbackModeHelper = AppDatabase.getInstance().playbackModeDao();
    public static long contentLength;
    public static FragmentSongBinding binding;
    public static String Singer, Name, Url;
    private String LrcPath, Pic, SongId = "123", time;
    //更新歌词的频率，每秒更新一次
    private final int mPalyTimerDuration = 1000;
    //更新歌词的定时器
    public static Timer mTimer;
    //更新歌词的定时任务
    public static TimerTask mTask;
    //    private MediaPlayer mPlayer;
    private int p;
    private boolean isPlaying;


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_song, container, false);
        EventBus.getDefault().register(this);//注册消息
        initstaus();//设置状态栏颜色
        initView();//初始化控件
        playbackModeHelper.initializeDefaultPlaybackMode();//初始化播放状态数据库
        return binding.getRoot();

    }

    //接收ListFragment中传递过来的消息数据
    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void NetPlayEventBus(ListToPlayEvent event) {
        //网络播放页背景图
        Glide.with(getActivity())
                .load(event.getPic())
                .error(R.mipmap.stackblur_default)
                .bitmapTransform(new BlurTransformation(Objects.requireNonNull(getActivity()), 200, 3))// 设置高斯模糊
                .into(binding.bgPhoto);
        //获取到了之后进行播放
        binding.NetPlayTitleMusic.setText(event.getName() + " - " + event.getSinger());//播放页歌曲标题
        LrcPath = event.getLrc();//获取歌单详情页传递过来的歌词API接口
        Url = event.getUrl();//获取播放地址
        Singer = event.getSinger();
        Name = event.getName();
        Pic = event.getPic();
        SongId = event.getSongId();
        binding.playTime.setText(event.getTime());
        //如果是正在播放的歌曲，那就直接进行还原，不用初始化，否则进行初始化
        time = event.getTime();
        long timeStr = TimeUtil.timeToSeconds(time);
        StarredSong newSong = new StarredSong(Singer, Name, SongId, timeStr, Pic, LrcPath, Url);
        checkFavoriteStatus(newSong);//检查是否收藏状态
        checkPlayMode();
        sendRequestWithOkHttp();//获取歌词

    }

    private void sendRequestWithOkHttp() {
        HttpUtil.sendOkHttpRequest(LrcPath, new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String lrc = null;//得到服务器返回歌词内容
                if (response.body() != null) {
                    lrc = response.body().string();
                }
                //解析歌词构造器
                ILrcBuilder builder = new DefaultLrcBuilder();
                //解析歌词返回LrcRow集合
                List<LrcRow> rows = builder.getLrcRows(lrc);
                binding.lrcView.setLrc(rows);//将得到的歌词集合传给mLrcView用来展示

            }
        });
    }

    /**
     * 开始播放歌曲并同步展示歌词
     */
    public void beginLrcPlay() {
        try {
//            mMediaPlayer.setDataSource(Url);//设置歌词播放地址
            System.out.println("没有在播放");
            checkUrlAvailability(mList.get(playPosition).getUrl());
            //准备播放歌曲监听
            //歌曲播放完毕监听


        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

    }

    /**
     * 停止展示歌曲
     */
    public void stopLrcPlay() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    /**
     * 展示歌曲的定时任务
     */
    public class LrcTask extends TimerTask {

        public void run() {
            //获取歌曲播放的位置
            final long timePassed = mediaPlayer.getCurrentPosition();
            binding.progress.setMax(mediaPlayer.getDuration());//设置SeekBar的长度
            getProgress();
//            Log.d("网络歌曲播放界面","歌曲播放位置的时间点："+timePassed);
            if (getActivity() == null) return;
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
//                    //滚动歌词
                    binding.lrcView.seekLrcToTime(timePassed);
                }
            });

        }
    }

    public void initView() {//按钮事件

        ViewPager headlow = Objects.requireNonNull(getActivity()).findViewById(R.id.play_viewpager);
        binding.playLow.setOnClickListener(new View.OnClickListener() {//下三角形返回
            @Override
            public void onClick(View v) {
                Objects.requireNonNull(getActivity()).finish();//跳转到歌曲列表页面
            }
        });
        binding.netPlayBack.setOnClickListener(new View.OnClickListener() {//左返回
            @Override
            public void onClick(View v) {
                Objects.requireNonNull(getActivity()).finish();//跳转到歌曲列表页面
            }
        });

        binding.button2.setOnClickListener(new View.OnClickListener() {//播放按钮监听
            @Override
            public void onClick(View v) {
                if (binding.NetPlayTitleMusic.equals("暂无歌曲")) {
                    Toast.makeText(getActivity(), "找不到歌曲", Toast.LENGTH_SHORT).show();
                }
                if (mediaPlayer.isPlaying()) {
                    musicService.pauseOrContinueMusic();
                    binding.button2.setImageResource(R.mipmap.m_icon_player_play_normal);
//                    binding.button2.setImageResource(R.mipmap.m_icon_player_pause_normal);
                } else {
//                    beginLrcPlay();
                    musicService.pauseOrContinueMusic();
                    binding.button2.setImageResource(R.mipmap.m_icon_player_pause_normal);
//                    mMediaPlayer.start();
                }//播放按钮显示图标判断
            }

        });


        binding.progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //取消timer任务
                stopLrcPlay();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //获取进度条的进度
                int p = seekBar.getProgress();
                //将进度条的进度赋值给歌曲
                mediaPlayer.seekTo(p);

                //开始音乐继续获取歌曲的进度
                getProgress();
            }
        });//进度条

        binding.lrcView.setListener(new ILrcViewListener() {//滑动歌词播放对应歌词
            @Override
            public void onLrcSeeked(int newPosition, LrcRow row) {
                if (mediaPlayer != null) {
//                    Log.d(TAG, "onLrcSeeked:" + row.time);
                    mediaPlayer.seekTo((int) row.time);
                }

            }
        });
        binding.btnFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFavorite(Singer, Name, SongId, Pic, LrcPath, Url, time);
            }
        });

        binding.buttonPlaylist.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SuspiciousIndentation")
            @Override
            public void onClick(View v) {
                // 这里写您的点击事件处理代码
                Intent intent = new Intent(getActivity(), PlayActivity.class);
                MyStarredSong = true;
                StarredSong song = starredSongHelper.getFirstStarredSong();
                if (song != null)
                    FindImgUrlPath = song.getPic();
                String ft = "我的收藏";
                EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                Objects.requireNonNull(getActivity()).startActivity(intent);
            }
        });

        binding.button1.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SuspiciousIndentation")
            @Override
            public void onClick(View v) {
                // 这里写您的点击事件处理代码
                //下一首,并且更新歌词显示
                musicService.previousMusic();

                beginLrcPlay();
            }
        });

        binding.button3.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SuspiciousIndentation")
            @Override
            public void onClick(View v) {
                // 这里写您的点击事件处理代码
                //发送数据到播放页，下一首歌
                musicService.nextMusic();
                beginLrcPlay();
            }
        });

        binding.btnFavorite1.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SuspiciousIndentation")
            @Override
            public void onClick(View v) {
                String currentMode = playbackModeHelper.getCurrentPlaybackMode(); // 读取当前播放模式
                String nextMode;
                int nextIconResId;

                // 根据当前模式决定下一个模式和对应图标
                switch (currentMode) {
                    case "list":
                        nextMode = "random";
                        nextIconResId = R.mipmap.random_cycle; // 随机播放图标
                        break;
                    case "random":
                        nextMode = "single";
                        nextIconResId = R.mipmap.single_cycle; // 单曲循环图标
                        break;
                    case "single":
                        nextMode = "list";
                        nextIconResId = R.mipmap.list_cycle; // 列表循环图标
                        break;
                    default:
                        nextMode = "list"; // 默认回到列表循环
                        nextIconResId = R.mipmap.list_cycle;
                        break;
                }

                // 更新数据库中的播放模式
                nowMode = nextMode;
                PlaybackMode newMode = new PlaybackMode(nextMode);
                newMode.id = 1; // 假设你的数据库中只有一条记录
                playbackModeHelper.updatePlaybackMode(newMode);

                // 更新按钮图标
                binding.btnFavorite1.setImageResource(nextIconResId);
            }
        });

    }

    //检查播放状态并更换图标
    private void checkPlayMode() {
        new Thread(() -> {
            String currentMode = playbackModeHelper.getCurrentPlaybackMode(); // 从数据库读取当前播放模式
            System.out.println("播放模式：" + currentMode);
            int iconResId;
            switch (currentMode) {
                case "random":
                    iconResId = R.mipmap.random_cycle; // 随机播放图标
                    break;
                case "single":
                    iconResId = R.mipmap.single_cycle; // 单曲循环图标
                    break;
                case "list":
                default:
                    iconResId = R.mipmap.list_cycle; // 列表循环图标
                    break;
            }
            binding.btnFavorite1.setImageResource(iconResId);
        }).start();
    }


    // 检查当前歌曲是否已被收藏，并更新按钮文本
    @SuppressLint("SuspiciousIndentation")
    private void checkFavoriteStatus(StarredSong newSong) {
        new Thread(() -> {
            StarredSong song = starredSongHelper.getStarredSongByNameAndSinger(newSong.getName(), newSong.getSinger()); // 假设 currentName 是当前歌曲的 ID
            Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
                if (song != null) {
                    binding.btnFavorite.setImageResource(R.mipmap.starred);
                    //如果已收藏，就直接将position获取然后进行播放；
                } else {
                    binding.btnFavorite.setImageResource(R.mipmap.no_star);
                    System.out.println("没有收藏");
                    //如果没有收藏，就将这首歌加入list，然后进行播放；
                }
                mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                    //准备完毕
                    public void onPrepared(MediaPlayer mp) {
//                    mp.start();
                        if (mTimer == null) {
                            mTimer = new Timer();
                            mTask = new LrcTask();
                            mTimer.scheduleAtFixedRate(mTask, 0, mPalyTimerDuration);
                        }
                    }
                });
                System.out.println("得到url" + newSong.getUrl());
                if (mediaPlayer.getDuration() == 0) {

                    if (starredSongHelper.getMaxId() != 0 && mList.get(playPosition).getUrl().equals(newSong.getUrl())) {
                        //
                        if (mediaPlayer.getDuration() != 0)
                            binding.playTime.setText(TimeUtil.formatSeconds(mediaPlayer.getDuration() / 1000));
                        System.out.println("和上一首歌一样");
                    } else {
                        System.out.println("没有放一样" + playPosition);
                        if (song != null) {
                            playPosition = song.getId() - 1;//注意修改数据库的时候需要把id同步修改
                        } else {
                            if (!mList.contains(newSong)) {
                                mList.add(newSong);
                                playPosition = mList.size() - 1;
                            }
                        }
                        //如果没有在播放我就直接显示歌词,并且播放
                        System.out.println("没有放一样www" + playPosition);
                        beginLrcPlay();
                    }
                } else {
                    System.out.println("正在播放ing" + newSong.getName() + mList.get(playPosition).getName() + playPosition + media_falg);
                    //检查这首歌和正在播放的歌曲是否一样，如果一样，就去还原他
                    if (mList.get(playPosition).getUrl().equals(newSong.getUrl())) {
                        System.out.println("播放与之前的一样");//并且还原现在的状态
//最好不要用不同步的方法
                        mTimer = new Timer();
                        mTask = new LrcTask();
                        mTimer.scheduleAtFixedRate(mTask, 0, mPalyTimerDuration);
                        binding.button2.setImageResource(R.mipmap.m_icon_player_play_normal);

                    } else {
                        System.out.println("播放与之前的不一样");
                        if (song != null) {
                            playPosition = song.getId() - 1;
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                boolean containsName = mList.stream().anyMatch(item -> item.getName().equals(newSong.getName()));
                                if (!containsName) {
                                    System.out.println("添加歌曲" + newSong.getName());
                                    mList.add(newSong);
                                    playPosition = mList.size() - 1;
                                }
                            }
                        }
                        CheckUrlToSet(newSong.getUrl());
                        media_falg = false;
                    }
                }

                if (mediaPlayer.getDuration() != 0)
                    binding.playTime.setText(TimeUtil.formatSeconds(mediaPlayer.getDuration() / 1000));
            });
        }).start();
    }

    // 切换当前歌曲的收藏状态
    private void toggleFavorite(String currentSinger, String currentSongName, String currentSongId,
                                String currentPic, String currentLrc,
                                String currentUrl, String Time) {
        new Thread(() -> {
            StarredSong song = starredSongHelper.getStarredSongByName(currentSongName);
            int id = starredSongHelper.getMaxId();
            System.out.println("最大id" + id);
            StarredSong newSong = new StarredSong();
            newSong.setSinger(currentSinger);
            newSong.setId(id + 1);
            newSong.setName(currentSongName);
            newSong.setSongId(currentSongId); // 确保这个ID是唯一标识
            newSong.setPic(currentPic); // 确保获取了正确的图片URL或路径
            newSong.setTime(1); // 假设 currentTime 是当前播放时间
            newSong.setLrc(currentLrc); // 假设 currentLrc 是歌词信息
            newSong.setUrl(currentUrl); // 假设 currentUrl 是歌曲URL
            newSong.setDownloaded(false); // 默认为未下载
            newSong.setAudioFilePath(""); // 如果有音频文件路径
            newSong.setTime(TimeUtil.timeToSeconds(Time));
            if (song != null) {
                starredSongHelper.deleteStarredSongByNameAndSinger(song.getName(), song.getSinger());
                starredSongHelper.updateWhereId(song.getId());
                mList = starredSongHelper.getAllStarredSongs();
                mList.add(newSong);
                playPosition = mList.size() - 1;
                Objects.requireNonNull(getActivity()).runOnUiThread(() -> binding.btnFavorite.setImageResource(R.mipmap.no_star));
            } else {
                starredSongHelper.insertSong(newSong);
                mList = starredSongHelper.getAllStarredSongs();
                playPosition = mList.size() - 1;
                Objects.requireNonNull(getActivity()).runOnUiThread(() -> binding.btnFavorite.setImageResource(R.mipmap.starred));

            }
        }).start();
    }

    //实时获取歌曲的进度
    private void getProgress() {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                //获取歌曲的进度
                p = mediaPlayer.getCurrentPosition();
                //将获取歌曲的进度赋值给seekbar
                binding.progress.setProgress(p);
                if (getActivity() == null) return;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.playTime1.setText(TimeUtil.ShowTime(p));
                    }
                });
            }
        }, 0, 1000);
    }


    //状态栏设置
    private void initstaus() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = Objects.requireNonNull(getActivity()).getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册
//        if (mMediaPlayer != null) {
//            mMediaPlayer.stop();
//        }
    }

    @SuppressLint("StaticFieldLeak")
    private void checkUrlAvailability(final String url) {
        if (url.startsWith("http")) {
            new AsyncTask<Void, Void, Boolean>() {
                @Override
                protected Boolean doInBackground(Void... voids) {
                    try {
                        URL urlObj = new URL(url);
                        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
                        connection.setRequestMethod("GET");
                        int responseCode = connection.getResponseCode();
                        contentLength = connection.getContentLength();
                        //可以请求
                        return responseCode == HttpURLConnection.HTTP_OK;
                    } catch (Exception e) {
                        //请求失败
                        e.printStackTrace();
                        return false;
                    }
                }

                @Override
                protected void onPostExecute(Boolean isAvailable) {
                    if (isAvailable) {
                        //可以播放

                        //进行时间长度解析
                        if (contentLength > 0) {
                            // 假设音频编码的比特率为128 kbps
                            long bitrate = 128000; // 比特率（比特每秒）
                            // 计算时长（秒）= 文件大小（字节） / 比特率（比特每秒） / 8（将比特转换为字节）
                            long durationInSeconds = (contentLength * 8) / bitrate;
                            System.out.println("时间长度 " + durationInSeconds + " seconds");

                        }
                        musicService.play(playPosition);
                        // URL可用，设置MediaPlayer的数据源

                        // 其他MediaPlayer的设置和准备操作...

                    } else {
                        //不可以播放
                        // URL不可用，处理错误，重新找一个url放入数据库
                        HttpUtil.sendOkHttpRequest("http://ovoa.cc/api/QQmusic.php?msg=" + Name + " " + Singer + "&n=1&type=json", new Callback() {
                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                e.printStackTrace();
                                //                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                                String ListResponseData = null;//得到服务器返回的具体内容
                                if (response.body() != null) {
                                    ListResponseData = response.body().string();
                                }
                                JSONObject jsonObject = null;
                                try {

                                    jsonObject = new JSONObject(ListResponseData);
                                    int code = jsonObject.getInt("code");
                                    if (code == 200) {
                                        JSONObject dataObject = jsonObject.getJSONObject("data");
                                        String url = dataObject.getString("src");
                                        //更新

                                        starredSongHelper.updateByNameAndSinger(Name, Singer, url);//放入数据库

                                    }


                                } catch (JSONException e) {


                                }
                            }
                        });

                    }
                }
            }.execute();
        } else {
            musicService.play(playPosition);
        }

    }

    //停止音乐
    @SuppressLint("StaticFieldLeak")
    private void CheckUrlToSet(String url) {
        if (url.startsWith("http")) {
            new AsyncTask<Void, Void, Boolean>() {
                @Override
                protected Boolean doInBackground(Void... voids) {
                    try {
                        URL urlObj = new URL(url);
                        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
                        connection.setRequestMethod("GET");
                        int responseCode = connection.getResponseCode();
                        //可以弄到Get
                        return responseCode == HttpURLConnection.HTTP_OK;
                    } catch (Exception e) {
                        //失败
                        e.printStackTrace();
                        return false;
                    }
                }

                @Override
                protected void onPostExecute(Boolean isAvailable) {
                    if (isAvailable) {
                        System.out.println("一样可以获取" + mList.get(playPosition).getName());
                        //可以播放
                        // URL可用，设置MediaPlayer的数据源
                        musicService.play(playPosition);
                        stopLrcPlay();
                        // 其他MediaPlayer的设置和准备操作...

                    } else {
                        //不可以播放
                        // URL不可用，处理错误，重新找一个url放入数据库
                        HttpUtil.sendOkHttpRequest("http://ovoa.cc/api/QQmusic.php?msg=" + Name + " " + Singer + "&n=1&type=json", new Callback() {
                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                                String ListResponseData = null;//得到服务器返回的具体内容
                                if (response.body() != null) {
                                    ListResponseData = response.body().string();
                                }
                                JSONObject jsonObject = null;
                                try {

                                    jsonObject = new JSONObject(ListResponseData);
                                    int code = jsonObject.getInt("code");
                                    if (code == 200) {
                                        JSONObject dataObject = jsonObject.getJSONObject("data");
                                        String url = dataObject.getString("src");
                                        //需要更新
                                        starredSongHelper.updateByNameAndSinger(Name, Singer, url);//放入数据库
                                        mList.get(playPosition).setUrl(url);
                                        //然后进行回调
                                        musicService.play(playPosition);
                                        stopLrcPlay();
                                        checkUrl(url);

                                    } else {
                                        HttpUtil.sendOkHttpRequest("https://www.hhlqilongzhu.cn/api/dg_kugouSQ.php?msg=" + Name + " " + Singer + "&n=1&type=json", new Callback() {
                                            @Override
                                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                                e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                                                String ListResponseData = null;//得到服务器返回的具体内容
                                                if (response.body() != null) {
                                                    ListResponseData = response.body().string();
                                                }
                                                JSONObject jsonObject = null;
                                                try {

                                                    jsonObject = new JSONObject(ListResponseData);
                                                    int code = jsonObject.getInt("code");
                                                    if (code == 200) {
                                                        String url = jsonObject.getString("music_url");
                                                        //需要更新
                                                        starredSongHelper.updateByNameAndSinger(Name, Singer, url);//放入数据库
                                                        mList.get(playPosition).setUrl(url);
                                                        //然后进行回调
                                                        musicService.play(playPosition);
                                                        stopLrcPlay();

                                                    } else {

                                                    }


                                                } catch (JSONException ignored) {


                                                }
                                            }
                                        });
                                    }


                                } catch (JSONException ignored) {

                                    HttpUtil.sendOkHttpRequest("https://www.hhlqilongzhu.cn/api/dg_kugouSQ.php?msg=" + Name + " " + Singer + "&n=1&type=json", new Callback() {
                                        @Override
                                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                            e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                                            String ListResponseData = null;//得到服务器返回的具体内容
                                            if (response.body() != null) {
                                                ListResponseData = response.body().string();
                                            }
                                            JSONObject jsonObject = null;
                                            try {

                                                jsonObject = new JSONObject(ListResponseData);
                                                int code = jsonObject.getInt("code");
                                                if (code == 200) {
                                                    String url = jsonObject.getString("music_url");
                                                    //需要更新
                                                    starredSongHelper.updateByNameAndSinger(Name, Singer, url);//放入数据库
                                                    mList.get(playPosition).setUrl(url);
                                                    //然后进行回调
                                                    musicService.play(playPosition);
                                                    stopLrcPlay();

                                                } else {

                                                }


                                            } catch (JSONException ignored) {


                                            }
                                        }
                                    });
                                }
                            }
                        });

                    }
                }
            }.execute();
        } else {
            musicService.play(playPosition);
            stopLrcPlay();
        }

    }

    private void checkUrl(String url) {
        if (url.startsWith("http")) {
            new AsyncTask<Void, Void, returnFormat>() {
                @Override
                protected returnFormat doInBackground(Void... voids) {
                    try {
                        URL urlObj = new URL(url);
                        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
                        connection.setRequestMethod("GET");
                        int responseCode = connection.getResponseCode();
                        long contentLength = connection.getContentLength();
                        //可以请求
                        return new returnFormat(responseCode == HttpURLConnection.HTTP_OK, contentLength);
                    } catch (Exception e) {
                        //请求失败
                        e.printStackTrace();
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(returnFormat isAvailable) {

                    if (isAvailable != null) {
                        //可以播放
                        //进行时间长度解析
                        if (isAvailable.getLength() > 0) {

                        } else {
                            System.out.println("请求不大");
                            HttpUtil.sendOkHttpRequest("https://www.hhlqilongzhu.cn/api/dg_kugouSQ.php?msg=" + Name + " " + Singer + "&n=1&type=json", new Callback() {
                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                                    String ListResponseData = null;//得到服务器返回的具体内容
                                    if (response.body() != null) {
                                        ListResponseData = response.body().string();
                                    }
                                    JSONObject jsonObject = null;
                                    try {

                                        jsonObject = new JSONObject(ListResponseData);
                                        int code = jsonObject.getInt("code");
                                        if (code == 200) {
                                            String url = jsonObject.getString("music_url");
                                            //需要更新
                                            starredSongHelper.updateByNameAndSinger(Name, Singer, url);//放入数据库
                                            mList.get(playPosition).setUrl(url);
                                            //然后进行回调
                                            musicService.play(playPosition);
                                            stopLrcPlay();

                                        } else {

                                        }


                                    } catch (JSONException ignored) {


                                    }
                                }
                            });
                        }

                    }

                }

            }.execute();
        } else {
            musicService.play(playPosition);
            stopLrcPlay();
        }


    }

}
